package com.example.client;

import com.example.config.AppConfig;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class OllamaClient {
    private static final Logger logger = LoggerFactory.getLogger(OllamaClient.class);
    private final String apiUrl;
    private final String model;

    public OllamaClient() {
        this.apiUrl = AppConfig.get("ollama.api.url", "http://8.141.3.36:11434/api/chat");
        this.model = AppConfig.get("ollama.model", "deepseek-r1:1.5b");
        logger.info("Ollama客户端初始化完成，使用模型: {}", model);
    }

    public String generateText(String prompt) throws IOException {
        return generateText(new ArrayList<>(Arrays.asList(new Message("user", prompt))));
    }

    public String generateText(List<Message> messages) throws IOException {
        logger.debug("发送请求到Ollama API，消息数量: {}", messages.size());
        
        URL url = new URL(apiUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);

        // 设置连接和读取超时（5秒连接，30秒读取）
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(30000);

        String requestBody = buildRequestBody(messages);
        try (java.io.OutputStream os = connection.getOutputStream()) {
            byte[] input = requestBody.getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }

        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                StringBuilder response = new StringBuilder();
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                String responseJson = response.toString();
                logger.debug("收到Ollama API响应: {}", responseJson);
                return parseResponse(responseJson);
            }
        } else {
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8))) {
                StringBuilder response = new StringBuilder();
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                String errorResponse = response.toString();
                logger.error("API调用失败，状态码: {}, 错误信息: {}", responseCode, errorResponse);
                throw new IOException("HTTP错误 " + responseCode + ": " + errorResponse);
            }
        }
    }

    private String buildRequestBody(List<Message> messages) {
        JSONObject requestBody = new JSONObject();
        requestBody.put("model", model);

        JSONArray messageArray = new JSONArray();
        for (Message message : messages) {
            JSONObject msgObj = new JSONObject();
            msgObj.put("role", message.getRole());
            msgObj.put("content", message.getContent());
            messageArray.put(msgObj);
        }
        requestBody.put("messages", messageArray);
        
        // Ollama API特定参数
        requestBody.put("stream", false);  // 不使用流式响应
        requestBody.put("temperature", AppConfig.getDouble("ollama.temperature", 0.7));
        requestBody.put("max_tokens", AppConfig.getInt("ollama.max_tokens", 1000));

        return requestBody.toString();
    }

    private String parseResponse(String responseJson) {
        // Ollama的响应格式: {"message":{"role":"assistant","content":"回复内容"}}
        JSONObject responseObj = new JSONObject(responseJson);
        JSONObject message = responseObj.getJSONObject("message");
        String content = message.getString("content");

        // 清理AI响应中的特殊标记和思考过程
        return cleanAiResponse(content);
    }

    private String cleanAiResponse(String response) {
        if (response == null || response.trim().isEmpty()) {
            logger.debug("AI响应为空，返回默认回复");
            return "抱歉，我暂时无法回复您的问题，请稍后再试。";
        }

        String originalResponse = response;
        logger.debug("开始清理AI响应，原始长度: {}", response.length());

        // 移除思考标记和相关内容
        response = response.replaceAll("\\\\n\\\\u003c/think.*?\\\\u003e", "");
        response = response.replaceAll("\\\\u003cthink\\\\u003e.*?\\\\u003c/think\\\\u003e", "");
        response = response.replaceAll("<think>.*?</think>", "");
        response = response.replaceAll("\\\\n\\\\u003c.*?\\\\u003e", "");

        // 移除多余的换行符和空格
        response = response.replaceAll("\\\\n", "\n");
        response = response.replaceAll("\\n+", "\n");
        response = response.trim();

        // 移除Unicode转义字符
        response = response.replaceAll("\\\\u([0-9a-fA-F]{4})", "");

        logger.debug("清理后响应长度: {}", response.length());
        if (!originalResponse.equals(response)) {
            logger.debug("响应已被清理，原始: [{}], 清理后: [{}]", originalResponse, response);
        }

        // 如果清理后内容为空，返回默认回复
        if (response.trim().isEmpty()) {
            logger.debug("清理后响应为空，返回默认回复");
            return "感谢您的咨询！我已经收到您的问题，如有疑问请联系人工客服。";
        }

        return response;
    }

    public static class Message {
        private final String role;
        private final String content;

        public Message(String role, String content) {
            this.role = role;
            this.content = content;
        }

        public String getRole() {
            return role;
        }

        public String getContent() {
            return content;
        }
    }
}    